<template>
  <div class="p-2">
    <!-- 物模型协议 - 产品管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="品类选择" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="请选择品类" clearable>
            <el-option v-for="category in categoryList" :key="category.categoryId" :label="category.categoryName"
              :value="category.categoryId" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(false)">删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品ID" prop="id" width="120" show-overflow-tooltip />
        <el-table-column label="产品名称" prop="name" width="180" show-overflow-tooltip />
        <el-table-column label="品类" prop="categoryName" width="140" show-overflow-tooltip />
        <el-table-column label="网络协议类型" prop="protocolType" width="140" align="center">
          <template #default="scope">
            <el-tag>{{ scope.row.protocolType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="170" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <ProductFormDialog v-model:visible="formDialogVisible" :data="currentFormData" :category-options="categoryList"
      :protocol-options="protocolOptions" @submit="handleFormSubmit" />

    <ProductDetailDialog v-model:visible="detailDialog.visible" :product-data="detailDialog.data" />

    <ThingModelDialog v-model:visible="thingModelDialog.visible" :product-data="thingModelDialog.data"
      :active-tab="thingModelTab" :properties-list="propertiesList" :functions-list="functionsList"
      :events-list="eventsList" />
  </div>
</template>

<script setup name="ProductManage" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { Search, Refresh, Plus, Edit, Delete, Download, Upload, CopyDocument, View, Setting, Monitor, DataAnalysis, Promotion } from '@element-plus/icons-vue'
import ProductFormDialog from './components/ProductFormDialog.vue'
import ProductDetailDialog from './components/ProductDetailDialog.vue'
import ThingModelDialog from './components/ThingModelDialog.vue'
// 移除远程API，改为本地模拟数据
// import { getCategoryList } from '@/api/IOT/protocolManage/categoryManage'
// import { getProductList, deleteProduct, exportProduct, addProduct, updateProduct } from '@/api/IOT/protocolManage/productManage'

// 模拟网络延迟
const delayRandom = (min = 200, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地模拟的品类数据
const mockCategories = ref([
  { categoryId: 1001, categoryName: '温湿度传感器' },
  { categoryId: 1002, categoryName: '智能网关' },
  { categoryId: 1003, categoryName: '视频监控' }
])

// 本地模拟的产品数据
const mockProducts = ref([
  { id: 'P10001', productId: 'P10001', name: '温湿度采集器A', productName: '温湿度采集器A', categoryId: 1001, categoryName: '温湿度传感器', protocolType: 'MQTT', status: 1, remark: '室内环境监测' },
  { id: 'P10002', productId: 'P10002', name: '智能网关X1', productName: '智能网关X1', categoryId: 1002, categoryName: '智能网关', protocolType: 'TCP', status: 1, remark: '支持多设备接入' },
  { id: 'P10003', productId: 'P10003', name: '摄像头B200', productName: '摄像头B200', categoryId: 1003, categoryName: '视频监控', protocolType: 'HTTP', status: 0, remark: '户外监控' },
  { id: 'P10004', productId: 'P10004', name: '温湿度采集器Pro', productName: '温湿度采集器Pro', categoryId: 1001, categoryName: '温湿度传感器', protocolType: 'MQTT', status: 1, remark: '高精度传感器' }
])

// 路由
const router = useRouter()

// 品类信息
const categoryInfo = reactive({
  id: '',
  name: ''
})

// 响应式数据
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const productList = ref([])
const categoryList = ref([])
const protocolOptions = ref([
  { label: 'TCP', value: 'TCP' },
  { label: 'HTTP', value: 'HTTP' },
  { label: 'MQTT', value: 'MQTT' },
  { label: 'UDP', value: 'UDP' }
])
const currentFormData = ref({})
const formDialogVisible = ref(false)
const propertiesList = ref([])
const functionsList = ref([])
const eventsList = ref([])
const thingModelTab = ref('properties')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  categoryId: '',
  name: ''
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 物模型对话框
const thingModelDialog = reactive({
  visible: false,
  data: null
})

// 获取协议标签样式
const getProtocolTag = (protocol: string) => {
  switch (protocol) {
    case 'mqtt': return 'primary'
    case 'coap': return 'success'
    case 'http': return 'warning'
    case 'tcp': return 'danger'
    case 'udp': return 'info'
    case 'modbus': return 'primary'
    default: return 'primary'
  }
}

// 获取数据格式标签样式
const getDataFormatTag = (format: string) => {
  switch (format) {
    case 'json': return 'success'
    case 'custom': return 'warning'
    case 'modbus': return 'primary'
    default: return 'primary'
  }
}

// 获取数据格式文本
const getDataFormatText = (format: string) => {
  switch (format) {
    case 'json': return 'JSON'
    case 'custom': return '透传'
    case 'modbus': return 'Modbus'
    default: return '未知'
  }
}

// 获取事件类型标签样式
const getEventTypeTag = (type: string) => {
  switch (type) {
    case 'info': return 'primary'
    case 'alert': return 'warning'
    case 'error': return 'danger'
    default: return 'primary'
  }
}

// 获取事件类型文本
const getEventTypeText = (type: string) => {
  switch (type) {
    case 'info': return '信息'
    case 'alert': return '告警'
    case 'error': return '故障'
    default: return '未知'
  }
}

// 查询产品列表（本地模拟数据）
const getList = async () => {
  loading.value = true
  await delayRandom()
  // 过滤
  let filtered = mockProducts.value
  if (queryParams.categoryId) {
    filtered = filtered.filter(item => String(item.categoryId) === String(queryParams.categoryId))
  }
  if (queryParams.name) {
    const kw = String(queryParams.name).toLowerCase()
    filtered = filtered.filter(item => String(item.name).toLowerCase().includes(kw) || String(item.productName).toLowerCase().includes(kw))
  }
  // 分页
  const start = (queryParams.pageNum - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  productList.value = filtered.slice(start, end)
  total.value = filtered.length
  loading.value = false
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.categoryId = ''
  queryParams.name = ''
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  currentFormData.value = {
    productId: '',
    categoryId: '',
    categoryName: '',
    name: '',
    protocolType: '',
    remark: ''
  }
  formDialogVisible.value = true
}

// 修改按钮操作
const handleUpdate = (row?: any) => {
  const productId = row?.id || ids.value[0]
  // 模拟获取详情
  const product = productList.value.find(item => item.id === productId)
  if (product) {
    currentFormData.value = {
      productId: product.id,
      categoryId: product.categoryId,
      categoryName: product.categoryName || '',
      name: product.name,
      protocolType: product.protocolType,
      remark: product.remark || ''
    }
  }
  formDialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  detailDialog.data = row
  detailDialog.visible = true
}

// 物模型配置
const handleThingModel = (row: any) => {
  thingModelDialog.data = row
  thingModelDialog.visible = true
  thingModelTab.value = 'properties'
  // 模拟物模型数据
  propertiesList.value = [
    {
      identifier: 'temperature',
      name: '温度',
      dataType: 'float',
      dataSpecs: '范围：-40~85，单位：°C',
      accessMode: 'r',
      required: true,
      description: '当前环境温度值'
    },
    {
      identifier: 'humidity',
      name: '湿度',
      dataType: 'float',
      dataSpecs: '范围：0~100，单位：%RH',
      accessMode: 'r',
      required: false,
      description: '当前环境湿度值'
    }
  ]
  functionsList.value = [
    {
      identifier: 'reset',
      name: '重置设备',
      callType: 'async',
      inputParams: '无',
      outputParams: '{"result": "success"}',
      description: '重置设备到出厂设置'
    }
  ]
  eventsList.value = [
    {
      identifier: 'temp_alert',
      name: '温度告警',
      eventType: 'alert',
      outputParams: '{"temperature": 85.5, "threshold": 80}',
      description: '温度超过阈值时触发'
    }
  ]
}

// 设备管理
const handleDeviceManage = (row: any) => {
  ElMessage.info('跳转到设备管理页面：' + row.productName)
}

// 协议管理
const handleProtocolManage = (row: any) => {
  // 跳转到协议管理页面，传递完整的级联参数
  ElMessage.success(`跳转到协议管理页面，产品：${row.productName}`)
  router.push({
    path: '/iot/protocolManage/protocolList',
    query: {
      productId: row.productId,
      productName: row.productName,
      categoryId: categoryInfo.id,
      categoryName: categoryInfo.name
    }
  })
}

// 数据解析
const handleDataParse = (row: any) => {
  ElMessage.info('跳转到数据解析页面：' + row.productName)
}

// 查看设备
const viewDevices = (row: any) => {
  ElMessage.info('跳转到设备列表页面：' + row.productName)
}

// 发布产品
const handlePublish = () => {
  ElMessageBox.confirm('确认发布选中的产品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('发布成功')
    getList()
  })
}

// 复制产品
const handleCopy = () => {
  ElMessage.info('复制产品功能开发中')
}

// 删除按钮操作（本地模拟数据）
const handleDelete = async (row?: any) => {
  let productIds: string[] = []
  let confirmMessage = ''
  if (row) {
    productIds = [row.id]
    confirmMessage = `确定要删除产品\"${row.productName || row.name}\"吗？删除后将无法恢复！`
  } else {
    productIds = ids.value as string[]
    confirmMessage = `确定要删除选中的 ${productIds.length} 个产品吗？删除后将无法恢复！`
  }
  if (productIds.length === 0) {
    ElMessage.warning('请选择要删除的产品')
    return
  }
  try {
    await ElMessageBox.confirm(confirmMessage, '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await delayRandom()
    mockProducts.value = mockProducts.value.filter(p => !productIds.includes(String(p.id)))
    ElMessage.success('删除成功')
    ids.value = []
    single.value = true
    multiple.value = true
    getList()
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 导出（CSV，基于本地数据）
const handleExport = async () => {
  await delayRandom()
  const headers = ['产品ID', '产品名称', '品类', '协议类型', '状态', '备注']
  const rows = productList.value.map((p: any) => [p.id, p.name, p.categoryName, p.protocolType, p.status === 1 ? '启用' : '停用', p.remark || ''])
  const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `产品列表_${new Date().getTime()}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}



// 物模型操作函数
const addProperty = () => {
  ElMessage.info('新增属性功能开发中')
}

const importProperties = () => {
  ElMessage.info('导入属性功能开发中')
}

const editProperty = (property: any) => {
  ElMessage.info('编辑属性：' + property.name)
}

const deleteProperty = (property: any) => {
  ElMessageBox.confirm('确认删除属性"' + property.name + '"？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const addFunction = () => {
  ElMessage.info('新增功能功能开发中')
}

const editFunction = (func: any) => {
  ElMessage.info('编辑功能：' + func.name)
}

const deleteFunction = (func: any) => {
  ElMessageBox.confirm('确认删除功能"' + func.name + '"？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const addEvent = () => {
  ElMessage.info('新增事件功能开发中')
}

const editEvent = (event: any) => {
  ElMessage.info('编辑事件：' + event.name)
}

const deleteEvent = (event: any) => {
  ElMessageBox.confirm('确认删除事件"' + event.name + '"？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 表单提交处理
const handleFormSubmit = async (formData: any) => {
  await delayRandom()
  if (formData.productId) {
    const idx = mockProducts.value.findIndex(p => String(p.id) === String(formData.productId))
    if (idx !== -1) {
      mockProducts.value[idx] = { ...mockProducts.value[idx], ...formData, id: formData.productId, name: formData.name || mockProducts.value[idx].name, productName: formData.name || mockProducts.value[idx].productName }
      ElMessage.success('编辑产品成功')
    } else {
      ElMessage.error('未找到该产品')
      return
    }
  } else {
    const newId = 'P' + String(Math.max(...mockProducts.value.map(p => Number(String(p.id).replace(/^P/, '')))) + 1).padStart(5, '0')
    const newItem = {
      id: newId,
      productId: newId,
      name: formData.name,
      productName: formData.name,
      categoryId: Number(formData.categoryId) || '',
      categoryName: mockCategories.value.find(c => String(c.categoryId) === String(formData.categoryId))?.categoryName || '',
      protocolType: formData.protocolType || 'MQTT',
      status: 1,
      remark: formData.remark || ''
    }
    mockProducts.value.unshift(newItem)
    ElMessage.success('新增产品成功')
  }
  formDialogVisible.value = false
  getList()
}

// 获取品类列表（本地模拟数据）
const getCategoryListData = async () => {
  await delayRandom()
  categoryList.value = mockCategories.value
}

// 返回品类管理
const goBackToCategory = () => {
  router.push('/iot/protocolManage/categoryManage')
}

// 组件挂载
onMounted(() => {
  const route = useRoute()
  if (route.query.categoryId) {
    categoryInfo.id = route.query.categoryId
    categoryInfo.name = route.query.categoryName || ''
  }
  getCategoryListData()
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.product-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon-uploader .icon {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 4px;
}

.icon-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.icon-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}
</style>